import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

import {
  renderWithQiankun,
  qiankunWindow,
} from "vite-plugin-qiankun/es/helper";

let instance: ReturnType<typeof createApp>;

function render(props: { container?: HTMLElement }) {
  // 动态确定挂载点
  const container = props.container || document.getElementById("app");
  // 确保容器元素存在
  if (!container) {
    throw new Error("MicroAppContainer element not found");
  }
  // 防止重复挂载
  if (instance) {
    instance.unmount();
    container.innerHTML = "";
  }

  instance = createApp(App);
  instance.use(router);
  instance.mount(container);
}
// 独立运行
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({});
} else {
  // 在 Qiankun 环境中，导出生命周期函数
  renderWithQiankun({
    mount(props) {
      render(props);
    },
    bootstrap() {
      console.log("vue3-app bootstrapped");
    },
    unmount() {
      if (instance) {
        instance.unmount();
      }
    },
    update() {
      console.log("vue3-app updated");
    },
  });
}
